package com.stockz.equity.dao;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.stereotype.Repository;

import com.stockz.equity.model.Bar;

@Repository
public class BarDaoImpl implements BarDao {

	@Autowired private JpaTemplate jpaTemplate;
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Bar> getBarListByScripCode(String scripCode){
		return jpaTemplate.findByNamedQuery(Bar.GetBarListByScripCodeQuery, new Object[]{scripCode});
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Bar> getBarListByScripCode(final String scripCode,final int count){
		if(count <= 0){
			return getBarListByScripCode(scripCode);
		}
		
		return jpaTemplate.executeFind(new JpaCallback<List<Bar>>(){
			@Override
			public List<Bar> doInJpa(EntityManager em)
					throws PersistenceException {
				Query query = em.createNamedQuery(Bar.GetBarListByScripCodeQuery);
				query.setParameter(1, scripCode);
				query.setMaxResults(count);
				return query.getResultList();
			}			
		});		
	}

	@Override
	public Date getLastDownloadDate() {
		return jpaTemplate.execute(new JpaCallback<Date>(){
			@Override
			public Date doInJpa(EntityManager em) throws PersistenceException {
				Query query = em.createQuery("select max(bar.date) from Bar bar");
				return (Date)query.getSingleResult();
			}
		});
	}
	
	@Override
	public void persist(Bar bar) {
			jpaTemplate.persist(bar);
	}
	
	@Override
	public void persistAll(final Collection<Bar> barList) {
		if(barList != null && !barList.isEmpty()){
			jpaTemplate.execute(new JpaCallback<Object>(){
				@Override
				public Object doInJpa(EntityManager em)
						throws PersistenceException {
					EntityTransaction transaction = em.getTransaction();
					transaction.begin();
					for(Bar bar : barList){
						if(bar != null){
							em.persist(bar);
						}
					}
					transaction.commit();
					return null;
				}
			});
		}
	}
	
}